package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.log.admin.LogMailDeductProperty;
import com.yanqu.road.entity.mail.AllMailLanguage;
import com.yanqu.road.entity.player.ServerMail;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserMail;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.logic.bussiness.mail.ServerMailBussiness;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.mail.MailModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.mail.ServerMailMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/game/admin")
public class AdminMailController {

    /**
     *  5.1 个人邮件发送
     */
    @ResponseBody
    @RequestMapping(value = "userMail", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String userMail(HttpServletRequest request, @RequestBody JSONObject paramObject){

        // 奖励
        String annexes = paramObject.getString("annexes").replace("|", ";");

        // 类型
        eMailType mailType = eMailType.MARKETING;
        // 玩家id列表
        List<Long> playerIdList = StringUtils.stringToLongList(paramObject.getString("userIds"), ",");

        //失败的玩家
        List<Long> failList = new ArrayList<>();

        AdminResult result = AdminResult.defaultInstance();

        long personalId = paramObject.getLongValue("personalId");

        int activityId = paramObject.getIntValue("activityId");

        // 多语言
        //邮件内容
        JSONArray jsonArray = paramObject.getJSONArray("contentList");

        Map<String, List<Long>> playerLanguageMap = new HashMap<>();
        // 统计多个语言
        for (long playerId : playerIdList) {
            UserInfo userInfo = UserMgr.getUserInfo(playerId);
            if (userInfo != null) {
                if (!playerLanguageMap.containsKey(userInfo.getLanguage())) {
                    playerLanguageMap.put(userInfo.getLanguage(), new ArrayList<>());
                }
                playerLanguageMap.get(userInfo.getLanguage()).add(playerId);
            }else {
                failList.add(playerId);
            }
        }

        for (String languageKey : playerLanguageMap.keySet()) {
            String title;
            String msg;
            String qrCode = "";
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String language = jsonObject.getString("language");
                if(languageKey.equals(language)){
                    title = jsonObject.getString("title");
                    msg = jsonObject.getString("content");
                    if (jsonObject.containsKey("qrCodeUrl")){
                        qrCode = jsonObject.getString("qrCodeUrl");
                    }

                    if(StringUtils.isNullOrEmpty(msg) || StringUtils.isNullOrEmpty(title)){
                        continue;
                    }

                    List<Long> userIdList = playerLanguageMap.get(languageKey);
                    for (Long id : userIdList) {
                        if(annexes == null || annexes.equals("null") || annexes.equals("")){
                            MailManager.sendMailAdmin(id, mailType.getValue(), "", msg, title, personalId, qrCode, activityId);
                        }else{
                            MailManager.sendMailAdmin(id, mailType.getValue(), annexes, msg, title, personalId, qrCode, activityId);
                        }
                    }
                    break;
                }
            }

        }

        if(failList.size() > 0){
            result.getData().put(String.valueOf(-1), failList);
        }

        return result.toJsonString();
    }


    /**
     *  5.2 群发邮件发送
     */
    @ResponseBody
    @RequestMapping(value = "serverMail", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String serverMail(HttpServletRequest request, @RequestBody JSONObject jsonObject){


        //邮件奖励
        String annexes = "";
        if(jsonObject.containsKey("annexes")){
            annexes = jsonObject.getString("annexes").replace("|", ";");
        }

        if(!jsonObject.containsKey("contentList")){
            return AdminResult.failMsg("contentList 为空").toJsonString();
        }

        String appId = jsonObject.getString("appId");

        int type = jsonObject.getIntValue("type");

        long massId = 0;
        if(jsonObject.containsKey("massId")){
            massId = jsonObject.getLongValue("massId");
        }

        AdminResult2 result = AdminResult2.defaultInstance();

        //邮件内容
        JSONArray jsonArray = jsonObject.getJSONArray("contentList");

        Set<String> appIdSet = new HashSet<>();

        long serverId = ConfigHelper.getLong("serverId");
        int channelId = ServerListMgr.getChannelId(serverId);

//        if (eChannelType.Hun1.getValue() == channelId || eChannelType.MainLandBusiness.getValue() == channelId || eChannelType.MainLandInnerTest.getValue() == channelId) {
//            //目前混服才有这个
//            if (!StringUtils.isNullOrEmpty(appId)) {
//                appIdSet.add(appId);
//            }
//        }
        if (!StringUtils.isNullOrEmpty(appId)) {
            appIdSet.add(appId);
        }

        String content = "";
        String title = "";
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            content = jsonObject1.getString("content");
            title = jsonObject1.getString("title");
            if(!StringUtils.isNullOrEmpty(content) && !StringUtils.isNullOrEmpty(title)) {
                break;
            }
        }
        if(StringUtils.isNullOrEmpty(content) || StringUtils.isNullOrEmpty(title)){
            ServerListMgr.getLogger().error("邮件没有默认内容标题");
            ServerListMgr.getLogger().error("========  {}", jsonObject.toJSONString());
            return AdminResult2.failMsg("多语言空").toJsonString();
        }


        ServerMail serverMail = ServerMailMgr.buildServerMail(eMailType.MARKETING.getValue(), title, content, annexes);
        serverMail.setMassId(massId);
        serverMail.setAppIdSet(appIdSet);
        ServerMailBussiness.addServerMail(serverMail);
        ServerMailMgr.getServerMailMap().put(serverMail.getMailId(), serverMail);


        // 生成语言模板
        Map<String, AllMailLanguage> map = new ConcurrentHashMap<>();

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            String msg = jsonObject1.getString("content");
            String tt = jsonObject1.getString("title");
            String language = jsonObject1.getString("language");

            if(StringUtils.isNullOrEmpty(msg) || StringUtils.isNullOrEmpty(tt)){
                continue;
            }

            AllMailLanguage data = new AllMailLanguage();
            data.setMailId(serverMail.getMailId());
            data.setLanguageType(language);
            data.setTitle(tt);
            data.setMsg(msg);

            ServerMailBussiness.addAllServerMailLanguage(data);
            map.put(language, data);
        }

        ServerMailMgr.getAllMailLanguageMap().put(serverMail.getMailId(), map);


        GamePlayerMgr.getCopyPlayerMap().values().forEach(p -> ServerMailMgr.playerGetServerMail(p));


        return result.toJsonString();

    }

    @ResponseBody
    @RequestMapping(value = "viewMailState", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String viewMailState(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        long personalId = jsonObject.getLongValue("personalId");
        if(personalId <= 0){
            return AdminResult.failMsg("personalId 无效参数").toJsonString();
        }

        if(!jsonObject.containsKey("userId")){
            return AdminResult.failMsg("userId 为空").toJsonString();
        }
        long userId = jsonObject.getLongValue("userId");

        //查库？
        //已删除？
        List<Integer> mailState = new AdminCommonDaoImpl().getMailState(personalId, userId);
        if(mailState.size() == 0){
            mailState = new AdminCommonDaoImpl().getDeletedMailState(personalId, userId);
        }

        AdminResult2 adminResult2 = AdminResult2.defaultInstance();
        if(mailState.size() == 2){
            JSONObject object = new JSONObject();
            object.put("userId", userId);
            object.put("viewStatus", mailState.get(0));
            object.put("claimStatus", mailState.get(1));
            adminResult2.getData().add(object);
        }

        return adminResult2.toJsonString();
    }

    /**
     * 73.1 角色邮件列表
     */
    @ResponseBody
    @RequestMapping(value = "characterMail/Query", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String queryMail(HttpServletRequest request, @RequestBody JSONObject jsonObject){
        long userId = jsonObject.getLongValue("userId"); // 用户ID
        int pageNum = jsonObject.getIntValue("pageNum"); // 页码
        int pageSize = jsonObject.getIntValue("pageSize"); // 页大小

        AdminResult result = AdminResult.defaultInstance();
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if (player == null) {
            result.setCode(-1);
            result.setMsg("玩家未找到");
            return result.toJsonString();
        }
        MailModule mailModule = player.getModule(MailModule.class);
        Map<String, UserMail> backendMailMap = mailModule.getBackendMailMap();
        List<UserMail> userMails = new ArrayList<>(backendMailMap.values());
        userMails.sort((a, b) -> b.getSendTime().compareTo(a.getSendTime()));

        result.getData().put("total", userMails.size());

        long serverId = ConfigHelper.getLong("serverId");
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);

        JSONArray jsonArray = new JSONArray();
        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);
        for (int i = startIndex; i < startIndex + pageSize && i < userMails.size(); i++) {
            UserMail mail = userMails.get(i);
            JSONObject obj = new JSONObject();
            obj.put("channelId", serverInfo.getChannelId()); // 渠道ID
            obj.put("mailUid", mail.getMailUid()); // 服务端邮件UID
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            obj.put("mailTime", sdf.format(mail.getSendTime())); // 时间
            obj.put("mailId", mail.getPersonalId()); // 后台邮件ID，非后台邮件为0

            int mailType = mail.getMailType();
            if (mailType == 0) { // 新后台显示转换 0-日常邮件；1-系统邮件
                mailType = 1;
            } else if (mailType == 2) {
                mailType = 0;
            }
            obj.put("mailType", mailType); // 邮件类型

            obj.put("mailTitle", mail.getTitle()); // 邮件标题
            obj.put("mailContent", mail.getContent()); // 邮件内容
            obj.put("readStatus", mail.isRead() ? 1 : 0); // 是否已读
            obj.put("getStatus", mail.isGetReward() ? 1 : 0); // 是否领奖

            String annexes = mail.getAnnexes();
            if (StringUtils.isNullOrEmpty(annexes)) {
                obj.put("propInfo", "|");
            } else {
                obj.put("propInfo", mail.getAnnexes().replace(";", "|")); // 道具
            }
            jsonArray.add(obj);
        }

        result.getData().put("rows", jsonArray);

        return result.toJsonString();
    }

    /**
     * 73.2 删除角色邮件（涉及扣除角色道具）
     */
    @ResponseBody
    @RequestMapping(value = "characterMail/remove", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String removeMail(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        long userId = jsonObject.getLongValue("userId"); // 用户ID
        String mailUid = jsonObject.getString("mailUid"); // 服务端邮件UID
        int isRecover = jsonObject.getIntValue("isRecover"); // 是否追回
        int isNegative = jsonObject.getIntValue("isNegative"); // 允许扣负

        AdminResult2 result = AdminResult2.defaultInstance();
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if (player == null) {
            result.setCode(-1);
            result.setMsg("玩家未找到");
            return result.toJsonString();
        }
        MailModule mailModule = player.getModule(MailModule.class);
        UserMail userMail = mailModule.getBackendUserMail(mailUid);
        if (userMail == null) {
            result.setCode(-1);
            result.setMsg("玩家邮件未找到");
            return result.toJsonString();
        }

        if (!userMail.isGetReward() && isRecover == 1) {
            result.setCode(-1);
            result.setMsg("玩家还未领取奖励，不能追回");
            return result.toJsonString();
        }
        if (isRecover == 0) { // 不追回
            if (mailModule.backendDeleteMail(mailUid)) {
                result.setMsg("邮件已删除");
            } else {
                result.setMsg("邮件未找到，删除失败");
            }
        } else if (isRecover == 1) { // 追回
            recover(player, userMail, isNegative, result);
        }

        return result.toJsonString();
    }

    /**
     * 追回道具
     *
     * @param player     player
     * @param userMail   userMail
     * @param isNegative 扣负
     * @param result     result
     */
    private void recover(GamePlayer player, UserMail userMail, int isNegative, AdminResult2 result) {
        CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
        BagModule bagModule = player.getModule(BagModule.class);
        MailModule mailModule = player.getModule(MailModule.class);
        String annexes = userMail.getAnnexes(); // 附件奖励道具
        Property property = PropertyHelper.parseStringToProperty(annexes);

        if (isNegative == 0) { // 不扣负
            Property goodsCanDeductMax = currencyModule.getGoodsCanDeductMax(bagModule, property);
            if (!currencyModule.removeCurrency(goodsCanDeductMax, eLogMoneyType.GM, eLogMoneyType.GmDeductGoods)) {
                result.setMsg("道具不扣负追回失败");
                return;
            }
            annexes = PropertyHelper.parsePropertyToString(goodsCanDeductMax);
        } else if (isNegative == 1) { // 扣负
            if (!currencyModule.forceRemoveCurrencyCanNegative(property)) {
                result.setMsg("道具扣负追回失败");
                return;
            }
        }
        AutoLogMgr.add(new LogMailDeductProperty(userMail.getReceiveUserId(), userMail.getAnnexes(), annexes, isNegative));
        if (mailModule.backendDeleteMail(userMail.getMailUid())) {
            result.setMsg("邮件已删除，共计删除玩家道具");
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(Arrays.asList(annexes.split(";")));
            result.setData(jsonArray);
        } else {
            result.setMsg("邮件未找到，删除失败");
        }
    }
}
